package com.qw.soul.permission.checker;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import android.view.WindowManager;

import androidx.core.app.NotificationManagerCompat;

import com.qw.soul.permission.PermissionActivityManager;
import com.qw.soul.permission.PermissionTools;
import com.qw.soul.permission.bean.Special;
import com.qw.soul.permission.debug.PermissionDebug;

import static android.os.Build.VERSION_CODES.O;

/**
 * @author cd5160866
 */
public class SpecialChecker implements PermissionChecker
{

    private static final String TAG = SpecialChecker.class.getSimpleName();

    private Context context;

    private Special permission;

    public SpecialChecker(Context context, Special permission)
    {
        this.context = context;
        this.permission = permission;
    }

    @Override
    public boolean check()
    {
        try
        {
            switch (permission)
            {
                case NOTIFICATION:
                    return checkNotification();
                case SYSTEM_ALERT:
                    return checkSystemAlert();
                case UNKNOWN_APP_SOURCES:
                    return checkUnknownSource();
                case DRAW_WINDOW:
                    return checkWindowDraw();
                default:
                    return true;
            }
        } catch (Exception e)
        {
            PermissionDebug.w(TAG, e.toString());
        }
        return true;
    }

    private boolean checkWindowDraw()
    {
        int sdkInt = Build.VERSION.SDK_INT;
        if (sdkInt >= 23)
        {
            return Settings.canDrawOverlays(context);
        }else
        {
            return new AppOpsChecker(context).checkOp(24);
        }
    }

    private boolean checkNotification()
    {
        return NotificationManagerCompat.from(context).areNotificationsEnabled();
    }

    private boolean checkSystemAlert()
    {
        if (!PermissionTools.isBelowAndroid6())
        {
            return Settings.canDrawOverlays(context);
        }
        return new AppOpsChecker(context).checkOp(24);
    }

    private boolean checkAlertPermission()
    {
        try
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(PermissionActivityManager.getInstance().getTopActivity());
            AlertDialog dialog = builder.setMessage("_").create();
            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            dialog.show();
            return true;
        }catch (Exception e)
        {
            return false;
        }
    }

    private boolean checkUnknownSource()
    {
        if (Build.VERSION.SDK_INT >= O)
        {
            return context.getPackageManager().canRequestPackageInstalls();
        }
        return true;
    }
}
